#!/bin/sh
# dua - Distributed User Archiver
# Synchronize all nodes files at the indicated location or current directory
#
# Copyright (c) 2000, 2001 by Clunix Inc. All Rights Reserved.
#


NODELIST=

USE_NOSYNCLIST="yes"
RSYNCOPTION="-azR --rsh=ssh"
VERBOSE="-v"

trap 'exit 0' 1 2 15

# Check option
while getopts l:n:daqh c; do
    case $c in
	l) NODELIST="$NODELIST `cat $OPTARG`"
	;;
	n) NODELIST="$NODELIST $OPTARG"
	;;
	d) RSYNCOPTION="$RSYNCOPTION --delete"
	;;
	a) USE_NOSYNCLIST="no"
	;;
	q) VERBOSE=""
	;;
	h) help=yes
	;;
	*) help=yesfail
	;;
    esac
done

if [ xxx$help != xxx ]; then
    cat <<EOF
Usage: dua [-n nodelist] [-l nodelist_file] [-daq] [files or directories...]
      -d : delete not existing options
      -a : do not use exclude-file list ~/.nosynclist nor /usr/clx/etc/nosynclist
      -q : suppress verbose output
      Default nodelist_file is ./.nodelist, ~/.nodelist or
      /usr/clx/etc/nodelist". If no file is defined, sync current directory
      Do not mix relative and absolute pathes for files and directories
EOF
    exit 1
fi

shift `expr $OPTIND - 1`

RSYNCOPTION="$RSYNCOPTION $VERBOSE"

# Get nodelist to synchronize
GREP=/bin/grep
if [ "$NODELIST" ];                then NODELIST="$NODELIST"
elif [ -f .nodelist ];             then NODELIST=`$GREP -v '^#' .nodelist`
elif [ -f ~/.nodelist ];           then NODELIST=`$GREP -v '^#' ~/.nodelist`
elif [ -f /usr/clx/etc/nodelist ]; then NODELIST=`$GREP -v '^#' /usr/clx/etc/nodelist`
fi
if [ -z "$NODELIST" ]; then
    echo "Cannot find nodes in .nodelist file at ./, ~/ nor /usr/clx/etc/"
    exit 1
fi


# Files not to be synchronized
if [ "$USE_NOSYNCLIST" = "yes" -a -f ~/.nosynclist ]; then
    EXCLUDE="--exclude-from=~/.nosynclist"
elif [ "$USE_NOSYNCLIST" = "yes" -a -f /usr/clx/etc/nosynclist ]; then
    EXCLUDE="--exclude-from=/usr/clx/etc/nosynclist"
else
    EXCLUDE=""
fi


# Get file list to synchronize

ARG1=$1

if [ "$#" -gt 1 ]; then shift; fi

# If source is not defined define it as .
if [ -z "$ARG1" ]; then ARG1=. ; fi

# If source is relative path, target is PWD
if [ "$ARG1" = "${ARG1#/}" ]; then DIR="$PWD" ; else DIR="/" ; fi


# Do loop for all nodes in NODELIST

for N in $NODELIST; do
    echo $N | grep '^#' >& /dev/null
    if [ $? -eq 0 ]; then
	continue
    fi
    # Do it node by node
    echo '###' synchronizing $N
    #(rsync $RSYNCOPTION $EXCLUDE $ARG1 $* $N:$DIR 2>&1) | sed -e "s/^/[$N] /"
    rsync $RSYNCOPTION $EXCLUDE $ARG1 $* $N:$DIR
done


exit 0

